package model

import (
	"encoding/json"
	"fmt"
)

func (order *Order) OrderVersion3(userId int, goodsId int, number int) bool {
	// 减库存
	if !checkStock(goodsId, number) {
		return false
	}

	// 下单
	order.UserId = userId
	order.GoodsId = goodsId
	order.Number = number

	// 分表
	tableIndex := userId / 10  % orderTableCount + 1
	tableName := fmt.Sprintf("orders_%d", tableIndex)
	if err := db.Table(tableName).Create(order).Error; err != nil {
		incrStock(goodsId, number)
		return false
	}

	// 发消息

	var orderMsg = new(OrderMsg)
	orderMsg.OrderId = order.Id
	orderMsg.GoodsId = order.GoodsId
	orderMsg.Number = order.Number
	orderMsg.UserId = order.UserId
	orderMsg.CreatedAt = order.CreatedAt

	jsonBytes, err := json.Marshal(orderMsg)
	if err != nil {
		fmt.Println(err)
	}

	err = mq.Publish("orderCreated", jsonBytes)
	if err != nil {
		fmt.Println(err)
	}

	return true
}

